/*
 * @Author: Lin Hongwei
 * @Date: 2022-10-08 20:17:08
 * @LastEditTime: 2022-11-05 15:32:50
 * @LastEditors: Lin Hongwei
 * @email: 1365755396@qq.com
 * @CSDN: https://blog.csdn.net/weixin_45429409
 * @Description: 看板的工具文件
 */

import { useMemo } from "react";
import { useLocation } from "react-router";
import { useQueryProjectDetail } from "../../../api/project";
import { useQueryTaskDetail } from "../../../api/task";
import { useDebouce } from "../../../hooks";
import { useUrlQueryParam } from "../../../hooks/url";

/**
 * @description: 从url中获取到项目的id
 * @return {*}
 */
export const useProjectIdInUrl = () => {
  const { pathname } = useLocation();
  const id = pathname.match(/projects\/(\d+)/)?.[1];
  return Number(id);
};

/**
 * @description: 根据url中的id查选项目信息
 * @return {*}
 */
export const useProjectInUrl = () => useQueryProjectDetail(useProjectIdInUrl());

/**
 * @description: 看板的请求参数
 * @return {*}
 */
export const useKanbanSearchParams = () => ({ projectId: useProjectIdInUrl() });
/**
 * @description: 看板的querykey
 * @return {*}
 */
export const useKanbanQueryKey = () => ["kanban", useKanbanSearchParams()];
export const useTaskSearchParams = () => {
  const [param] = useUrlQueryParam([
    "name",
    "processorId", //经办人
    "typeId", //任务类型
  ]);
  const projectId = useProjectIdInUrl();
  const debouceName = useDebouce(param.name, 1000);
  return useMemo(
    () => ({
      projectId,
      // name: param.name,
      name: debouceName,
      processorId: Number(param.processorId) || undefined,
      typeId: Number(param.typeId) || undefined,
    }),
    [projectId, param, debouceName]
  );
};
export const useTaskQueryKey = () => ["task", useTaskSearchParams()];

export const useTaskModal = () => {
  const [{ taskId, showTaskModal }, setUrlParam] = useUrlQueryParam([
    "taskId",
    "showTaskModal",
  ]);
  const { data: taskDetailData } = useQueryTaskDetail(+taskId);
  const queryTaskDetailFromID = (taskId: number) =>
    setUrlParam({ showTaskModal: true, taskId });
  const open = () => setUrlParam({ showTaskModal: true });
  const close = () =>
    setUrlParam({ showTaskModal: undefined, taskId: undefined });
  return {
    visible: showTaskModal == "true",
    taskDetailData,
    queryTaskDetailFromID,
    open,
    close,
  };
};
